package com.controller;

import com.entity.VehicleDailyMileage;
import com.service.VehicleDailyMileageService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/vehicle/daily/mileage")
public class VehicleDailyMileageController {

    @Autowired
    private VehicleDailyMileageService vehicleDailyMileageService;

    @PostMapping
    public VehicleDailyMileage create(@RequestBody VehicleDailyMileage vehicleDailyMileage) {
        return vehicleDailyMileageService.save(vehicleDailyMileage);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        vehicleDailyMileageService.deleteById(id);
    }

    @PutMapping("/{id}")
    public VehicleDailyMileage update(@PathVariable(value = "id") Integer id, @RequestBody VehicleDailyMileage vehicleDailyMileage) {
        vehicleDailyMileage.setId(id);
        return vehicleDailyMileageService.save(vehicleDailyMileage);
    }


    @GetMapping("/{id}")
    public VehicleDailyMileage detail(@PathVariable(value = "id") Integer id) {
        return vehicleDailyMileageService.findById(id).orElse(null);

    }

    @GetMapping("/page")
    public Page<VehicleDailyMileage> page(@RequestParam(defaultValue = "1") int pageNum,
                                                  @RequestParam(defaultValue = "10") int pageSize,
                                                  @RequestParam(required = false) String plateNumber) {
        Page<VehicleDailyMileage> page;
        if (plateNumber != null && !plateNumber.isEmpty()) {
            page = vehicleDailyMileageService.findByPlateNumberContaining(plateNumber, pageNum, pageSize);
        } else {
            page = vehicleDailyMileageService.findAll(pageNum, pageSize);
        }
        return page;
    }
}